<template>
  <p-card class="product-execu-wrap" :bordered="false">
    <div class="table-page-search-wrapper">
      <p-row type="flex" :gutter="24">
        <p-col flex="auto">
          <p-form layout="inline">
            <p-row :gutter="24">
              <p-col :xl="6" :md="12">
                <p-form-item label="二级工序">
                  <p-tree-select
                    v-model="queryParam.processTwoCode"
                    :tree-data="secondStations"
                    :dropdown-style="{maxHeight: '500px'}"
                    tree-node-filter-prop="title"
                    show-search
                    allow-clear
                    tree-default-expand-all
                  />
                </p-form-item>
              </p-col>
              <p-col :xl="6" :md="12">
                <p-form-item label="线体">
                  <p-select v-model="queryParam.lineCode" allow-clear>
                    <p-select-option
                      v-for="item in lines"
                      :key="item.codeValue"
                      :value="item.codeValue"
                    >{{ item.textValue }}</p-select-option>
                  </p-select>
                </p-form-item>
              </p-col>
              <p-col :xl="6" :md="12">
                <p-form-item label="工单状态">
                  <p-select v-model="queryParam.billStatus" allow-clear>
                    <p-select-option
                      v-for="item in orderStatusOptions"
                      :key="item.value"
                      :value="item.value"
                    >{{ item.label }}</p-select-option>
                  </p-select>
                </p-form-item>
              </p-col>
              <p-col :xl="6" :md="12">
                <p-form-item label="关键字">
                  <p-input v-model.trim="queryParam.keyword" />
                </p-form-item>
              </p-col>
            </p-row>
          </p-form>
        </p-col>
        <p-col style="padding-top: 2px;">
          <p-button type="primary" icon="search" @click="searchQuery">查询</p-button>
          <p-button class="ml10" type="primary" icon="reload" @click="searchReset">重置</p-button>
        </p-col>
      </p-row>
    </div>
    <div class="table-operator">
      <p-dropdown :disabled="disabled" class="ml10">
        <p-button type="primary">工单调整</p-button>
        <p-menu slot="overlay" @click="adjust">
          <p-menu-item key="pause">
            <a href="javascript:;">工单暂停</a>
          </p-menu-item>
          <p-menu-item key="start">
            <a href="javascript:;">工单启动</a>
          </p-menu-item>
        </p-menu>
      </p-dropdown>
      <p-button class="ml10" type="primary">超领物料</p-button>
      <p-button class="ml10" type="primary">生产退料</p-button>
      <!-- 高级查询区域 -->
      <j-super-query
        :fieldList="fieldList"
        ref="superQueryModal"
        @handleSuperQuery="handleSuperQuery"
      />
      <p-popover class="float-right" title="自定义列" trigger="click" placement="leftBottom">
        <template slot="content">
          <p-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
            <p-row>
              <template v-for="(item,index) in defColumns">
                <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                    <p-col :span="12"><p-checkbox :value="item.dataIndex">{{ item.title }}</p-checkbox></p-col>
                </template>
              </template>
            </p-row>
          </p-checkbox-group>
        </template>
        <a><p-icon type="setting" />自定义列</a>
      </p-popover>
    </div>
    <p-table
      ref="table"
      size="middle"
      bordered
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :scroll="{x: '100%'}"
      :row-selection="{ columnWidth: 40, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
    </p-table>

  </p-card>
</template>

<script>
import Vue from 'vue'
import mesPeProcessApi from '@/api/mesPeProcess'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JSuperQuery from '@/components/jeecg/JSuperQuery.vue'
import { getAction, postAction } from '@/api/manage'
import { ajaxGetDictItems } from '@/api/api'
const orderStatusOptions = [
      {
        value: -1,
        label: '已删除'
      },
      {
        value: 0,
        label: '未发布'
      },
      {
        value: 1,
        label: '已发布'
      },
      {
        value: 2,
        label: '已开工'
      },
      {
        value: 3,
        label: '已暂停'
      },
    ]
const fieldList = [
  {
    value: 'processType',
    text: '工单类型',
    type: 'select',
    options: []
  },
  {
    value: 'taskSource',
    text: '任务来源',
    type: 'select',
    options: [
      {
        value: '0',
        label: '主生产计划'
      }
    ]
  },
  {
    value: 'productionNo',
    text: '生产工单',
    type: 'String',
  },
  {
    value: 'processBillNo',
    text: '工序工单',
    type: 'String',
  },
  {
    value: 'processTwoName',
    text: '二级工序',
    type: 'String',
  },
  {
    value: 'lineName',
    text: '线体',
    type: 'String',
  },
  {
    value: 'productCode',
    text: '产品编号',
    type: 'String',
  },
  {
    value: 'productName',
    text: '产品名称',
    type: 'String',
  },
  {
    value: 'planQty',
    text: '计划数量',
    type: 'String',
  },
  {
    value: 'processStatus',
    text: '工单状态',
    options: orderStatusOptions
  },
  {
    value: 'startTime',
    text: '生产开工时间',
    type: 'datetime',
  },
  {
    value: 'endTime',
    text: '生产完工时间',
    type: 'datetime',
  },
  {
    value: 'quantityCompletion',
    text: '完成数量',
    type: 'int',
  },
  {
    value: 'classtimename',
    text: '班次',
    type: 'string',
  },
  {
    value: 'productionScheduling',
    text: '排产数量',
    type: 'int',
  },
  {
    value: 'scheduleTime',
    text: '排产日期',
    type: 'datetime',
  },
]

export default {
  name: 'ProductionExecution',
  mixins: [JeecgListMixin],
  components: {
    JSuperQuery
  },
  data() {
    return {
      fieldList,
      orderStatusOptions,
      queryParam: {
        processTwoCode: '',
        lineCode: '',
        stationCode: '',
        billStatus: ''
      },
      lines: [],
      processTree: [],
      columns: [],
      settingColumns: [],
      defColumns: [
        {
          title: '序号',
          dataIndex: 'rowIndex',
          width: 40,
          align: 'center',
          customRender(text, record, index) {
            return index + 1
          }
        },
        {
          title: '工单类型',
          dataIndex: 'processType',
          width: 70,
          align: 'center',
          customRender: text => this.processTypeData[text.toString()] || ''
        },
        {
          title: '任务来源',
          dataIndex: 'taskSource',
          width: 70,
          align: 'center',
        },
        {
          title: '生产工单',
          dataIndex: 'productionNo',
          width: 130,
          align: 'center',
        },
        {
          title: '工序工单',
          dataIndex: 'processBillNo',
          width: 150,
          align: 'center',
        },
        {
          title: '二级工序',
          dataIndex: 'processTwoName',
          width: 100,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '线体',
          dataIndex: 'lineName',
          width: 100,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '产品编号',
          dataIndex: 'productCode',
          width: 90,
          align: 'center',
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          width: 100,
          align: 'center',
          ellipsis: true,
        },
        {
          title: '计划数量',
          dataIndex: 'planQty',
          width: 70,
          align: 'center',
        },
        {
          title: '工单状态',
          dataIndex: 'processStatus',
          width: 70,
          align: 'center',
          customRender(text) {
            let label
            switch (text) {
              case -1:
                label = '已删除'
                break
              case 0:
                label = '未发布'
                break
              case 1:
                label = '已发布'
                break
              case 2:
                label = '已开工'
                break
              case 3:
                label = '已暂停'
                break
            }

            return label
          }
        },
        {
          title: '生产开工时间',
          dataIndex: 'startTime',
          width: 100,
          align: 'center',
        },
        {
          title: '生产完工时间',
          dataIndex: 'endTime',
          width: 100,
          align: 'center',
        },
        {
          title: '完成数量',
          dataIndex: 'quantityCompletion',
          width: 70,
          align: 'center',
        },
        {
          title: '班次',
          dataIndex: 'classtimename',
          width: 100,
          align: 'center',
        },
        {
          title: '排产数量',
          dataIndex: 'productionScheduling',
          width: 70,
          align: 'center',
        },
        {
          title: '排产日期',
          dataIndex: 'scheduleTime',
          width: 100,
          align: 'center',
        },
      ],
      processTypeData: {},
      selectedRowKeys: [],
    }
  },
  computed: {
    disabled() {
      return !this.selectedRowKeys.length
    },
    qisParams() {
      const barCode = this.barCode
      const stationCode = this.params.stationCode
      return {
        barCode,
        stationCode
      }
    },
    secondStations() {
      const data = []
      this.processTree.forEach(item => {
        const children = []
        item.children.forEach(child => {
          children.push({
            title: child.processmname,
            value: child.processmcode,
          })
        })
        data.push({
          disabled: true,
          title: item.processmname,
          value: item.processmcode,
          children
        })
      })
      
      return data
    }
  },
  created() {
    this.getLines()
    this.getStations()
    this.getProcessTypes()
    this.initColumns()
  },
  methods: {
    getProcessTypes() {
      ajaxGetDictItems('production_order_type').then(res => {
        this.fieldList[0].options = res.data
        const data = {}
        res.data.forEach(item => {
          data[item.value] = item.text
        })
        this.processTypeData = data
      })
    },
    getLines() {
      const params = {
        startDate: '2020-01-01 00:00:00',
        endDate: '2120-01-01 23:59:59'
      }
      getAction('/mes-manufacture/mfProcess/getFilter', params).then(res => {
        this.lines = res.data.lines
      })
    },
    getStations() {
      mesPeProcessApi.getProcesstree().then(res => {
        this.processTree = res.data || []
      })
    },
    loadData(arg) {
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() // 查询条件
      this.loading = true
      postAction('/mes-manufacture/mfStartWork/getStartWorkProcessBill', params).then((res) => {
        if (res.success) {
          this.dataSource = res.data.records
          this.ipagination.total = res.data.total
        }
        if (res.code === 510) {
          this.$message.warning(res.msg)
        }
        this.loading = false
      })
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ":colsettings";
      let colSettings = Vue.ls.get(key);
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = [];
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex);
        });
        this.settingColumns = allSettingColumns;
        this.columns = this.defColumns;
      } else {
        this.settingColumns = colSettings;
        const cols = this.defColumns.filter((item) => {
          if (item.key == "rowIndex" || item.dataIndex == "action") {
            return true;
          }
          if (colSettings.includes(item.dataIndex)) {
            return true;
          }
          return false;
        });
        this.columns = cols;
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ":colsettings";
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000);
      this.settingColumns = checkedValues;
      const cols = this.defColumns.filter((item) => {
        if (item.key == "rowIndex" || item.dataIndex == "action") {
          return true;
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true;
        }
        return false;
      });
      this.columns = cols;
    },
    onSelectChange(selectedRowKeys ) {
      this.selectedRowKeys  = selectedRowKeys
    },
    adjust({ key }) {
      let content = '确定要启动选中的工单吗？'
      let success = '工单启动成功'
      let status = 2
      if (key === 'pause') {
        content = '确定要暂停选中的工单吗？'
        success = '工单暂停成功'
        status = 3
      }
      this.$confirm({
        content,
        onOk: () => {
          const data = {
            processIds: this.selectedRowKeys,
            status
          }
          postAction('/mes-manufacture/mfStartWork/getStartWorkProcessAdjust', data).then(res => {
            if (res.data) {
              this.$message.success(success)
              this.loadData()
            } else {
              res.msg && this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>
